package com.homework.dao;

import com.homework.config.SpringConfig;
import com.homework.entity.User;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import lombok.extern.slf4j.Slf4j;

import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Repository;

import java.sql.*;


/**
 * @desc:
 * @author: Ping
 * @date: 2024/9/17 23:35
 */

@Repository
@Configuration
@Slf4j
public class UserDao {
    private SpringConfig springConfig;
    private Connection conn ;

    public int insert(User user) {
        /**
         * todo: 写出对应的sql
         */
        String sql = "INSERT INTO user (user_id,username, password, salt,nickname,email,phone,sex,age,img,status,create_time,update_time,last_login_time) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)" ;
        try (
                PreparedStatement ps =  conn.prepareStatement(sql) ;
                ){
            ps.setInt(1, User.getUser_Id()); ;
            ps.setString(2, User.getName()) ;
            ps.setString(3, User.getPassword()) ;
            ps.setString(4, User.getSalt()) ;
            ps.setString(5, User.getNickname()) ;
            ps.setString(6, User.getEmail()) ;
            ps.setString(7, User.getPhone()) ;
            ps.setInt(8, User.getGender());
            ps.setInt(9, User.getAge()) ;
            ps.setString(10, User.getImg()) ;
            ps.setInt(11, User.getStatus());
            ps.setDate(12, new Date(User.getCreate_time().getTime()));
            ps.setDate(13, new Date(User.getUpdate_time().getTime()));
            ps.setDate(14, new Date(User.getLast_login_time().getTime()));

        } catch (SQLException e) {
            /**
             * todo: 异常输出
             */
            log.error(e.getMessage()) ;
        }
        return 0 ;
    }
    public int selectCount() throws SQLException{
        ApplicationContext context=new AnnotationConfigApplicationContext(SpringConfig.class);
        SpringConfig springConfig1=context.getBean(SpringConfig.class);
        conn=springConfig1.getConnection();
        log.info("select count for all user in UserDao");
        String sql="select count(*) from user";

        ResultSet rs=conn.prepareStatement(sql).executeQuery();
        rs.next();
        int count=rs.getInt(1);
        return count;
    }

    /**
     * todo: 实现登录
     * @param name
     * @param password
     * @return
     */
    public User login(String name, String password) {
        return null ;
    }

    /**
     * todo: 统计所有的用户数
     * @return
     */
    public int countAllUsers() {
        return 0 ;
    }


}
